const WebSocket = require('ws');
const express = require('express');
const path = require('path');
const { v4: uuidv4 } = require('uuid');

const app = express();
const PORT = process.env.PORT || 13000;

// 静态文件服务
app.use(express.static(__dirname));

const server = app.listen(PORT, '0.0.0.0', () => {
    console.log(`游戏服务器运行在 http://localhost:${PORT}`);
    console.log(`局域网访问地址: http://0.0.0.0:${PORT}`);
    console.log(`其他设备可通过您的IP地址访问游戏`);
});

// WebSocket服务器
const wss = new WebSocket.Server({ server });

// 游戏配置
const GAME_CONFIG = {
    // 默认画布尺寸（会根据客户端动态调整）
    CANVAS_WIDTH: 1920,
    CANVAS_HEIGHT: 1080,
    // 世界尺寸是画布的6倍（扩充2倍）
    WORLD_WIDTH: 11520, // 1920 * 6
    WORLD_HEIGHT: 6480, // 1080 * 6
    GRID_SIZE: 20,
    INITIAL_SNAKE_LENGTH: 3,
    FOOD_COUNT: 60,     // 基础食物数量
    POWER_UP_COUNT: 35, // 基础道具数量
    GAME_SPEED: 150, // ms
    MAX_PLAYERS: 20,
    // 道具密度配置（每平方像素的道具数量）
    POWER_UP_DENSITY: 0.000015, // 根据地图面积动态调整道具数量（增加到原来的1.9倍）
    FOOD_DENSITY: 0.00006       // 根据地图面积动态调整食物数量（增加到原来的2倍）
};

// 动态更新世界尺寸的函数
function updateWorldSize(canvasWidth, canvasHeight) {
    GAME_CONFIG.CANVAS_WIDTH = canvasWidth;
    GAME_CONFIG.CANVAS_HEIGHT = canvasHeight;
    GAME_CONFIG.WORLD_WIDTH = canvasWidth * 3;
    GAME_CONFIG.WORLD_HEIGHT = canvasHeight * 3;
    
    console.log(`世界尺寸已更新: ${GAME_CONFIG.WORLD_WIDTH}x${GAME_CONFIG.WORLD_HEIGHT}`);
}

// 妖怪配置 - 数量越少长度越长，速度越慢
const MONSTER_TYPES = {
    DAWANG: {
        id: 'dawang',
        name: '大王洞大王',
        level: 1,
        color: '#FF0000',
        textColor: '#FFFFFF',
        size: 1.2,
        speed: 1.0,        // 调整速度，避免过快导致碰撞
        initialLength: 170, // 用户要求的长度
        scoreReward: 50,
        spawnChance: 0.3
    },
    LAOSHU: {
        id: 'laoshu',
        name: '老鼠精',
        level: 2,
        color: '#8B4513',
        textColor: '#FFFF00',
        size: 1.5,
        speed: 0.7,        // 调整速度
        initialLength: 320, // 用户要求的长度
        scoreReward: 100,
        spawnChance: 0.2
    },
    HUANGMEI: {
        id: 'huangmei',
        name: '黄眉大王',
        level: 3,
        color: '#FFD700',
        textColor: '#FF0000',
        size: 2.0,
        speed: 0.5,        // 调整速度
        initialLength: 560, // 用户要求的长度
        scoreReward: 200,
        spawnChance: 0.1
    }
};

// 游戏状态
const gameState = {
    players: new Map(),
    monsters: new Map(),
    foods: [],
    powerUps: [],
    gameStarted: false,
    worldMessages: []
};

// 道具类型
const POWER_UP_TYPES = {
    SPEED_BOOST: { id: 'speed', color: '#FFD700', duration: 5000, name: '加速' },
    INVINCIBLE: { id: 'invincible', color: '#FF69B4', duration: 3000, name: '无敌' },
    DOUBLE_SCORE: { id: 'double', color: '#00CED1', duration: 8000, name: '双倍分数' },
    SHRINK: { id: 'shrink', color: '#FF4500', duration: 0, name: '缩小' },
    GROW: { id: 'grow', color: '#32CD32', duration: 0, name: '变大' },
    INVISIBLE: { id: 'invisible', color: '#9370DB', duration: 4000, name: '隐身' },
    SHIELD: { id: 'shield', color: '#4169E1', duration: 6000, name: '护盾' },
    MAGNET: { id: 'magnet', color: '#FF1493', duration: 7000, name: '磁铁' },
    // 新增道具类型
    TELEPORT: { id: 'teleport', color: '#FF6347', duration: 0, name: '传送' },
    FREEZE: { id: 'freeze', color: '#87CEEB', duration: 4000, name: '冰冻' },
    LIGHTNING: { id: 'lightning', color: '#FFFF00', duration: 0, name: '闪电' },
    MULTI_FOOD: { id: 'multifood', color: '#FFA500', duration: 10000, name: '多倍食物' },
    GHOST: { id: 'ghost', color: '#DDA0DD', duration: 5000, name: '穿墙' },
    REVERSE: { id: 'reverse', color: '#DC143C', duration: 0, name: '反转' }
};

// 生成随机位置
function getRandomPosition(worldWidth = GAME_CONFIG.WORLD_WIDTH, worldHeight = GAME_CONFIG.WORLD_HEIGHT) {
    // 优先在地图中心区域生成玩家，避免出生在边缘
    const centerX = worldWidth / 2;
    const centerY = worldHeight / 2;
    const spawnRadius = Math.min(worldWidth, worldHeight) * 0.3; // 30%的范围
    
    const angle = Math.random() * 2 * Math.PI;
    const distance = Math.random() * spawnRadius;
    
    const x = Math.floor((centerX + Math.cos(angle) * distance) / GAME_CONFIG.GRID_SIZE) * GAME_CONFIG.GRID_SIZE;
    const y = Math.floor((centerY + Math.sin(angle) * distance) / GAME_CONFIG.GRID_SIZE) * GAME_CONFIG.GRID_SIZE;
    
    // 确保位置在世界边界内，留出足够的移动空间
    // 边界检测使用 >= worldWidth，所以最大有效坐标是 worldWidth - GRID_SIZE
    const clampedX = Math.max(GAME_CONFIG.GRID_SIZE * 2, Math.min(worldWidth - GAME_CONFIG.GRID_SIZE * 2, x));
    const clampedY = Math.max(GAME_CONFIG.GRID_SIZE * 2, Math.min(worldHeight - GAME_CONFIG.GRID_SIZE * 2, y));
    
    return { x: clampedX, y: clampedY };
}

// 检查位置是否被占用
function isPositionOccupied(pos) {
    // 检查是否与其他蛇重叠
    for (let player of gameState.players.values()) {
        if (player.alive) {
            for (let segment of player.snake) {
                if (segment.x === pos.x && segment.y === pos.y) {
                    return true;
                }
            }
        }
    }
    return false;
}

// 生成食物 - 优化分布算法
function generateFood() {
    gameState.foods = [];
    
    // 根据地图面积动态调整食物数量
    const worldArea = GAME_CONFIG.WORLD_WIDTH * GAME_CONFIG.WORLD_HEIGHT;
    const foodCount = Math.max(Math.floor(worldArea * GAME_CONFIG.FOOD_DENSITY), 50); // 最少50个食物
    
    console.log(`生成食物: 地图面积=${worldArea}, 食物数量=${foodCount}`);
    
    // 优化网格化分布算法 - 使用更小的网格增加分散性
    const gridCols = Math.ceil(GAME_CONFIG.WORLD_WIDTH / (GAME_CONFIG.GRID_SIZE * 8)); // 每8格一个网格，增加分散性
    const gridRows = Math.ceil(GAME_CONFIG.WORLD_HEIGHT / (GAME_CONFIG.GRID_SIZE * 8));
    const totalGrids = gridCols * gridRows;
    const foodPerGrid = Math.max(1, Math.floor(foodCount / totalGrids));
    const extraFoods = foodCount % totalGrids;
    
    let foodsGenerated = 0;
    
    // 在每个网格中生成食物
    for (let row = 0; row < gridRows && foodsGenerated < foodCount; row++) {
        for (let col = 0; col < gridCols && foodsGenerated < foodCount; col++) {
            const gridX = col * GAME_CONFIG.GRID_SIZE * 8;
            const gridY = row * GAME_CONFIG.GRID_SIZE * 8;
            const gridWidth = Math.min(GAME_CONFIG.GRID_SIZE * 8, GAME_CONFIG.WORLD_WIDTH - gridX);
            const gridHeight = Math.min(GAME_CONFIG.GRID_SIZE * 8, GAME_CONFIG.WORLD_HEIGHT - gridY);
            
            // 每个网格生成基础数量的食物
            let currentGridFoods = foodPerGrid;
            // 前几个网格额外生成一个食物
            if (extraFoods > 0 && (row * gridCols + col) < extraFoods) {
                currentGridFoods++;
            }
            
            for (let f = 0; f < currentGridFoods && foodsGenerated < foodCount; f++) {
                let attempts = 0;
                let pos;
                
                do {
                    // 增加随机偏移，让食物在网格内更分散
                    const localX = Math.floor(Math.random() * (gridWidth / GAME_CONFIG.GRID_SIZE)) * GAME_CONFIG.GRID_SIZE;
                    const localY = Math.floor(Math.random() * (gridHeight / GAME_CONFIG.GRID_SIZE)) * GAME_CONFIG.GRID_SIZE;
                    // 添加小范围随机偏移（0-3个格子）
                    const offsetX = (Math.random() < 0.7) ? Math.floor(Math.random() * 4) * GAME_CONFIG.GRID_SIZE : 0;
                    const offsetY = (Math.random() < 0.7) ? Math.floor(Math.random() * 4) * GAME_CONFIG.GRID_SIZE : 0;
                    pos = {
                        x: Math.min(gridX + localX + offsetX, GAME_CONFIG.WORLD_WIDTH - GAME_CONFIG.GRID_SIZE),
                        y: Math.min(gridY + localY + offsetY, GAME_CONFIG.WORLD_HEIGHT - GAME_CONFIG.GRID_SIZE)
                    };
                    attempts++;
                } while (isPositionOccupied(pos) && attempts < 20);
                
                if (attempts < 20) {
                    gameState.foods.push({
                        id: uuidv4(),
                        x: pos.x,
                        y: pos.y,
                        value: Math.floor(Math.random() * 3) + 1 // 1-3分
                    });
                    foodsGenerated++;
                }
            }
        }
    }
    
    console.log(`实际生成食物数量: ${foodsGenerated}`);
}

// 生成道具
function generatePowerUp() {
    const x = Math.floor(Math.random() * (GAME_CONFIG.CANVAS_WIDTH / GAME_CONFIG.GRID_SIZE)) * GAME_CONFIG.GRID_SIZE;
    const y = Math.floor(Math.random() * (GAME_CONFIG.CANVAS_HEIGHT / GAME_CONFIG.GRID_SIZE)) * GAME_CONFIG.GRID_SIZE;
    
    // 检查翻倍道具数量限制
    const currentDoubleCount = gameState.powerUps.filter(p => p.type === 'double').length;
    const doubleProb = currentDoubleCount >= 5 ? 0 : 0.025; // 如果已达上限则概率为0
    
    // 优化道具权重分布 - 翻倍道具数量限制在5个以内
    const powerUpTypes = [
        { type: 'mine', probability: 0.01 },     
        { type: 'double', probability: doubleProb },  // 动态概率
        { type: 'speed', probability: 0.3 },     
        { type: 'grow', probability: 0.25 },     
        { type: 'magnet', probability: 0.18 },   
        { type: 'shield', probability: 0.18 },   
        { type: 'shrink', probability: 0.155 }   
    ];
    
    const random = Math.random();
    let selectedType = 'speed'; // 默认类型改为speed
    let cumulative = 0;
    
    for (const powerUp of powerUpTypes) {
        if (powerUp.probability > 0) { // 只考虑概率大于0的道具
            cumulative += powerUp.probability;
            if (random <= cumulative) {
                selectedType = powerUp.type;
                break;
            }
        }
    }
    
    return {
        id: uuidv4(),
        x: x,
        y: y,
        type: selectedType,
        createdAt: Date.now()
    };
}

// 生成道具 - 优化分布算法
function generatePowerUps() {
    gameState.powerUps = [];
    
    // 根据地图面积和玩家数量动态调整道具数量
    const worldArea = GAME_CONFIG.WORLD_WIDTH * GAME_CONFIG.WORLD_HEIGHT;
    const basePowerUpCount = Math.floor(worldArea * GAME_CONFIG.POWER_UP_DENSITY);
    const playerBonus = Math.floor(gameState.players.size / 2);
    const powerUpCount = Math.max(basePowerUpCount + playerBonus, 25); // 最少25个道具
    
    console.log(`生成道具: 地图面积=${worldArea}, 基础道具数=${basePowerUpCount}, 玩家奖励=${playerBonus}, 总道具数=${powerUpCount}`);
    
    // 优化网格化分布算法 - 使用更小的网格增加分散性
    const gridCols = Math.ceil(GAME_CONFIG.WORLD_WIDTH / (GAME_CONFIG.GRID_SIZE * 10)); // 每10格一个网格，增加分散性
    const gridRows = Math.ceil(GAME_CONFIG.WORLD_HEIGHT / (GAME_CONFIG.GRID_SIZE * 10));
    const totalGrids = gridCols * gridRows;
    const powerUpPerGrid = Math.max(1, Math.floor(powerUpCount / totalGrids));
    const extraPowerUps = powerUpCount % totalGrids;
    
    let powerUpsGenerated = 0;
    let doubleCount = 0;
    const maxDoubleCount = 5;
    
    // 在每个网格中生成道具
    for (let row = 0; row < gridRows && powerUpsGenerated < powerUpCount; row++) {
        for (let col = 0; col < gridCols && powerUpsGenerated < powerUpCount; col++) {
            const gridX = col * GAME_CONFIG.GRID_SIZE * 10;
            const gridY = row * GAME_CONFIG.GRID_SIZE * 10;
            const gridWidth = Math.min(GAME_CONFIG.GRID_SIZE * 10, GAME_CONFIG.WORLD_WIDTH - gridX);
            const gridHeight = Math.min(GAME_CONFIG.GRID_SIZE * 10, GAME_CONFIG.WORLD_HEIGHT - gridY);
            
            // 每个网格生成基础数量的道具
            let currentGridPowerUps = powerUpPerGrid;
            // 前几个网格额外生成一个道具
            if (extraPowerUps > 0 && (row * gridCols + col) < extraPowerUps) {
                currentGridPowerUps++;
            }
            
            for (let p = 0; p < currentGridPowerUps && powerUpsGenerated < powerUpCount; p++) {
                let attempts = 0;
                let pos;
                
                do {
                    // 增加随机偏移，让道具在网格内更分散
                    const localX = Math.floor(Math.random() * (gridWidth / GAME_CONFIG.GRID_SIZE)) * GAME_CONFIG.GRID_SIZE;
                    const localY = Math.floor(Math.random() * (gridHeight / GAME_CONFIG.GRID_SIZE)) * GAME_CONFIG.GRID_SIZE;
                    // 添加小范围随机偏移（0-5个格子）
                    const offsetX = (Math.random() < 0.8) ? Math.floor(Math.random() * 6) * GAME_CONFIG.GRID_SIZE : 0;
                    const offsetY = (Math.random() < 0.8) ? Math.floor(Math.random() * 6) * GAME_CONFIG.GRID_SIZE : 0;
                    pos = {
                        x: Math.min(gridX + localX + offsetX, GAME_CONFIG.WORLD_WIDTH - GAME_CONFIG.GRID_SIZE),
                        y: Math.min(gridY + localY + offsetY, GAME_CONFIG.WORLD_HEIGHT - GAME_CONFIG.GRID_SIZE)
                    };
                    attempts++;
                } while (isPositionOccupied(pos) && attempts < 20);
                
                if (attempts < 20) {
                    // 生成道具类型
                    let powerUpType;
                    
                    // 优先生成翻倍道具（限制在5个以内）
                    if (doubleCount < maxDoubleCount && Math.random() < 0.15) {
                        powerUpType = 'double';
                        doubleCount++;
                    } else {
                        // 生成其他类型道具
                        const powerUpTypes = [
                            { type: 'speed', probability: 0.35 },
                            { type: 'grow', probability: 0.25 },
                            { type: 'magnet', probability: 0.18 },
                            { type: 'shield', probability: 0.15 },
                            { type: 'shrink', probability: 0.07 }
                        ];
                        
                        const random = Math.random();
                        let cumulative = 0;
                        powerUpType = 'speed'; // 默认类型
                        
                        for (const powerUp of powerUpTypes) {
                            cumulative += powerUp.probability;
                            if (random <= cumulative) {
                                powerUpType = powerUp.type;
                                break;
                            }
                        }
                    }
                    
                    gameState.powerUps.push({
                        id: uuidv4(),
                        x: pos.x,
                        y: pos.y,
                        type: powerUpType,
                        createdAt: Date.now()
                    });
                    powerUpsGenerated++;
                }
            }
        }
    }
    
    console.log(`实际生成道具数量: ${powerUpsGenerated}, 翻倍道具: ${doubleCount}`);
}

// 创建妖怪
function createMonster(type) {
    // 映射新的类型标识符到原有的妖怪类型
    const typeMapping = {
        'DAWANG': 'DAWANG',
        'LAOSHU': 'LAOSHU', 
        'HUANGMEI': 'HUANGMEI'
    };
    
    const actualType = typeMapping[type] || type;
    const monsterType = MONSTER_TYPES[actualType];
    if (!monsterType) return null;
    
    const monster = {
        id: uuidv4(),
        type: monsterType.id,
        name: monsterType.name,
        level: monsterType.level,
        color: monsterType.color,
        textColor: monsterType.textColor,
        size: monsterType.size,
        speed: monsterType.speed,
        scoreReward: monsterType.scoreReward,
        snake: [],
        direction: { x: GAME_CONFIG.GRID_SIZE, y: 0 },
        alive: true,
        lastMove: Date.now(),
        moveCounter: 0,
        targetPlayer: null,
        lastDirectionChange: Date.now()
    };
    
    // 生成出生位置 - 为妖怪蛇身预留足够空间
    let startPos;
    let attempts = 0;
    
    // 计算当前妖怪类型需要的安全边距
    const safeMargin = monsterType.initialLength * GAME_CONFIG.GRID_SIZE;
    
    do {
        // 在安全区域内生成位置
        const safeX = Math.floor(Math.random() * (GAME_CONFIG.WORLD_WIDTH - 2 * safeMargin) / GAME_CONFIG.GRID_SIZE) * GAME_CONFIG.GRID_SIZE + safeMargin;
        const safeY = Math.floor(Math.random() * (GAME_CONFIG.WORLD_HEIGHT - 2 * safeMargin) / GAME_CONFIG.GRID_SIZE) * GAME_CONFIG.GRID_SIZE + safeMargin;
        
        startPos = { x: safeX, y: safeY };
        attempts++;
    } while (isPositionOccupied(startPos) && attempts < 50);
    
    // 如果50次尝试后仍未找到合适位置，使用默认安全位置
    if (attempts >= 50) {
        startPos = {
            x: safeMargin + GAME_CONFIG.GRID_SIZE,
            y: safeMargin + GAME_CONFIG.GRID_SIZE
        };
    }
    
    // 初始化妖怪蛇身 - 确保所有身体部分都在边界内
    for (let i = 0; i < monsterType.initialLength; i++) {
        let segmentX = startPos.x - i * GAME_CONFIG.GRID_SIZE;
        let segmentY = startPos.y;
        
        // 确保身体部分不超出边界
        if (segmentX < 0) {
            segmentX = startPos.x + i * GAME_CONFIG.GRID_SIZE;
        }
        if (segmentX >= GAME_CONFIG.WORLD_WIDTH) {
            segmentX = startPos.x - i * GAME_CONFIG.GRID_SIZE;
        }
        
        monster.snake.push({
            x: segmentX,
            y: segmentY
        });
    }
    
    // 随机初始方向
    const directions = [
        { x: GAME_CONFIG.GRID_SIZE, y: 0 },
        { x: -GAME_CONFIG.GRID_SIZE, y: 0 },
        { x: 0, y: GAME_CONFIG.GRID_SIZE },
        { x: 0, y: -GAME_CONFIG.GRID_SIZE }
    ];
    monster.direction = directions[Math.floor(Math.random() * directions.length)];
    
    return monster;
}

// 妖怪AI移动逻辑
function moveMonster(monster) {
    if (!monster.alive) return;
    
    const now = Date.now();
    const speedDelay = GAME_CONFIG.GAME_SPEED / monster.speed;
    
    // 根据速度控制移动频率
    if (now - monster.lastMove < speedDelay) {
        return;
    }
    
    monster.lastMove = now;
    monster.moveCounter++;
    
    // 初始化妖怪智能记忆系统
    if (!monster.memory) {
        monster.memory = {
            lastPlayerPositions: new Map(),
            huntingTarget: null,
            patrolPath: [],
            currentPatrolIndex: 0,
            lastPlayerDirection: new Map()
        };
    }
    
    // 寻找最近的玩家作为目标，并更新记忆
    let nearestPlayer = null;
    let nearestDistance = Infinity;
    
    for (let [playerId, player] of gameState.players) {
        if (!player.alive) continue;
        
        const distance = Math.abs(player.snake[0].x - monster.snake[0].x) + 
                        Math.abs(player.snake[0].y - monster.snake[0].y);
        
        // 更新玩家位置和方向记忆
        monster.memory.lastPlayerPositions.set(playerId, {
            position: { x: player.snake[0].x, y: player.snake[0].y },
            timestamp: now
        });
        monster.memory.lastPlayerDirection.set(playerId, player.direction);
        
        if (distance < nearestDistance) {
            nearestDistance = distance;
            nearestPlayer = player;
        }
    }
    
    // 智能AI决策：追击玩家或探索移动
    if (nearestPlayer && nearestDistance < GAME_CONFIG.GRID_SIZE * 25) { // 扩大追击范围
        // 追击模式 - 智能预测追击策略
        monster.targetPlayer = nearestPlayer;
        const head = monster.snake[0];
        const target = nearestPlayer.snake[0];
        
        // 预测玩家下一步位置（基于玩家当前方向）
        const playerDirection = monster.memory.lastPlayerDirection.get(nearestPlayer.id);
        let predictedTarget = { x: target.x, y: target.y };
        
        if (playerDirection) {
            // 预测玩家2-3步后的位置进行拦截
            const predictionSteps = Math.min(3, Math.floor(nearestDistance / (GAME_CONFIG.GRID_SIZE * 5)));
            predictedTarget = {
                x: target.x + playerDirection.x * predictionSteps,
                y: target.y + playerDirection.y * predictionSteps
            };
            
            // 确保预测位置在地图范围内
            predictedTarget.x = Math.max(0, Math.min(GAME_CONFIG.WORLD_WIDTH - GAME_CONFIG.GRID_SIZE, predictedTarget.x));
            predictedTarget.y = Math.max(0, Math.min(GAME_CONFIG.WORLD_HEIGHT - GAME_CONFIG.GRID_SIZE, predictedTarget.y));
        }
        
        // 计算到预测目标的方向
        const dx = predictedTarget.x - head.x;
        const dy = predictedTarget.y - head.y;
        
        // 生成多个可能的方向选择
        const possibleDirections = [];
        
        // 主要方向（直接朝向目标）
        if (Math.abs(dx) > Math.abs(dy)) {
            possibleDirections.push({ x: dx > 0 ? GAME_CONFIG.GRID_SIZE : -GAME_CONFIG.GRID_SIZE, y: 0, priority: 5 });
            if (dy !== 0) {
                possibleDirections.push({ x: 0, y: dy > 0 ? GAME_CONFIG.GRID_SIZE : -GAME_CONFIG.GRID_SIZE, priority: 4 });
            }
        } else {
            possibleDirections.push({ x: 0, y: dy > 0 ? GAME_CONFIG.GRID_SIZE : -GAME_CONFIG.GRID_SIZE, priority: 5 });
            if (dx !== 0) {
                possibleDirections.push({ x: dx > 0 ? GAME_CONFIG.GRID_SIZE : -GAME_CONFIG.GRID_SIZE, y: 0, priority: 4 });
            }
        }
        
        // 添加其他方向作为备选
        const allDirections = [
            { x: GAME_CONFIG.GRID_SIZE, y: 0 },
            { x: -GAME_CONFIG.GRID_SIZE, y: 0 },
            { x: 0, y: GAME_CONFIG.GRID_SIZE },
            { x: 0, y: -GAME_CONFIG.GRID_SIZE }
        ];
        
        allDirections.forEach(dir => {
            if (!possibleDirections.some(pd => pd.x === dir.x && pd.y === dir.y)) {
                possibleDirections.push({ ...dir, priority: 2 });
            }
        });
        
        // 按优先级排序并检查安全性
        possibleDirections.sort((a, b) => b.priority - a.priority);
        
        let chosenDirection = null;
        for (let dir of possibleDirections) {
            const nextHead = {
                x: head.x + dir.x,
                y: head.y + dir.y
            };
            
            // 只检查基本安全性（不撞墙、不撞自己），移除边界限制
            const wouldHitWall = nextHead.x < 0 || nextHead.x >= GAME_CONFIG.WORLD_WIDTH || 
                                nextHead.y < 0 || nextHead.y >= GAME_CONFIG.WORLD_HEIGHT;
            const wouldHitSelf = monster.snake.some(segment => 
                segment.x === nextHead.x && segment.y === nextHead.y);
            
            // 只要不撞墙不撞自己就可以选择
            if (!wouldHitWall && !wouldHitSelf) {
                chosenDirection = dir;
                break; // 找到安全方向就停止
            }
        }
        
        if (chosenDirection) {
            monster.direction = chosenDirection;
        }
    } else {
        // 探索移动模式 - 更智能的路径选择
        if (now - monster.lastDirectionChange > 3000 || Math.random() < 0.15) {
            const directions = [
                { x: GAME_CONFIG.GRID_SIZE, y: 0 },
                { x: -GAME_CONFIG.GRID_SIZE, y: 0 },
                { x: 0, y: GAME_CONFIG.GRID_SIZE },
                { x: 0, y: -GAME_CONFIG.GRID_SIZE }
            ];
            
            // 评估每个方向的安全性和开阔性
            const directionScores = directions.map(dir => {
                const nextHead = {
                    x: monster.snake[0].x + dir.x,
                    y: monster.snake[0].y + dir.y
                };
                
                let score = 0;
                
                // 基本安全检查
                const wouldHitWall = nextHead.x < 0 || nextHead.x >= GAME_CONFIG.WORLD_WIDTH || 
                                    nextHead.y < 0 || nextHead.y >= GAME_CONFIG.WORLD_HEIGHT;
                const wouldHitSelf = monster.snake.some(segment => 
                    segment.x === nextHead.x && segment.y === nextHead.y);
                
                if (wouldHitWall || wouldHitSelf) {
                    return { direction: dir, score: -1000 }; // 完全不可行
                }
                
                // 鼓励探索整个地图，而不是避开边界
                const centerX = GAME_CONFIG.WORLD_WIDTH / 2;
                const centerY = GAME_CONFIG.WORLD_HEIGHT / 2;
                const distanceToCenter = Math.sqrt(
                    Math.pow(nextHead.x - centerX, 2) + Math.pow(nextHead.y - centerY, 2)
                );
                // 给予轻微的随机性，避免所有妖怪都聚集在中心
                score += Math.random() * 15 - distanceToCenter / (GAME_CONFIG.GRID_SIZE * 50);
                
                // 前方开阔性检查
                let openSpace = 0;
                for (let i = 1; i <= 5; i++) {
                    const checkPos = {
                        x: nextHead.x + dir.x * i,
                        y: nextHead.y + dir.y * i
                    };
                    
                    if (checkPos.x >= 0 && checkPos.x < GAME_CONFIG.WORLD_WIDTH &&
                        checkPos.y >= 0 && checkPos.y < GAME_CONFIG.WORLD_HEIGHT &&
                        !monster.snake.some(segment => segment.x === checkPos.x && segment.y === checkPos.y)) {
                        openSpace++;
                    } else {
                        break;
                    }
                }
                score += openSpace * 5;
                
                // 避免频繁改变方向
                if (dir.x === monster.direction.x && dir.y === monster.direction.y) {
                    score += 20;
                }
                
                return { direction: dir, score };
            });
            
            // 选择得分最高的方向
            const validDirections = directionScores.filter(ds => ds.score > -1000);
            if (validDirections.length > 0) {
                validDirections.sort((a, b) => b.score - a.score);
                monster.direction = validDirections[0].direction;
                monster.lastDirectionChange = now;
            }
        }
    }
    
    // 移动妖怪
    const head = { ...monster.snake[0] };
    head.x += monster.direction.x;
    head.y += monster.direction.y;
    
    // 边界检查 - 使用当前实际的世界尺寸
    const currentWorldWidth = GAME_CONFIG.WORLD_WIDTH;
    const currentWorldHeight = GAME_CONFIG.WORLD_HEIGHT;
    
    // 只在真正撞墙时才改变方向，允许妖怪接近边界
    if (head.x < 0 || head.x >= currentWorldWidth || 
        head.y < 0 || head.y >= currentWorldHeight) {
        // 妖怪接近或撞到边界时智能改变方向
        const directions = [
            { x: GAME_CONFIG.GRID_SIZE, y: 0 },
            { x: -GAME_CONFIG.GRID_SIZE, y: 0 },
            { x: 0, y: GAME_CONFIG.GRID_SIZE },
            { x: 0, y: -GAME_CONFIG.GRID_SIZE }
        ];
        
        // 找到安全的方向，优先选择远离边界的方向
        const validDirections = directions.filter(dir => {
            const testHead = {
                x: monster.snake[0].x + dir.x,
                y: monster.snake[0].y + dir.y
            };
            
            // 确保不会撞墙且不会撞到自己
            const wouldHitWall = testHead.x < 0 || testHead.x >= currentWorldWidth || 
                                testHead.y < 0 || testHead.y >= currentWorldHeight;
            const wouldHitSelf = monster.snake.some(segment => 
                segment.x === testHead.x && segment.y === testHead.y);
            
            return !wouldHitWall && !wouldHitSelf;
        });
        
        // 如果有安全方向，优先选择朝向地图中心的方向
        if (validDirections.length > 0) {
            const centerX = currentWorldWidth / 2;
            const centerY = currentWorldHeight / 2;
            const currentX = monster.snake[0].x;
            const currentY = monster.snake[0].y;
            
            // 按照朝向中心的优先级排序
            validDirections.sort((a, b) => {
                const aHead = { x: currentX + a.x, y: currentY + a.y };
                const bHead = { x: currentX + b.x, y: currentY + b.y };
                
                const aDistanceToCenter = Math.abs(aHead.x - centerX) + Math.abs(aHead.y - centerY);
                const bDistanceToCenter = Math.abs(bHead.x - centerX) + Math.abs(bHead.y - centerY);
                
                return aDistanceToCenter - bDistanceToCenter;
            });
            
            monster.direction = validDirections[0];
            // 重新计算头部位置
            head.x = monster.snake[0].x + monster.direction.x;
            head.y = monster.snake[0].y + monster.direction.y;
        } else {
            // 如果没有有效方向，尝试后退
            const reverseDirection = {
                x: -monster.direction.x,
                y: -monster.direction.y
            };
            
            const reverseHead = {
                x: monster.snake[0].x + reverseDirection.x,
                y: monster.snake[0].y + reverseDirection.y
            };
            
            const canReverse = reverseHead.x >= 0 && reverseHead.x < currentWorldWidth && 
                              reverseHead.y >= 0 && reverseHead.y < currentWorldHeight &&
                              !monster.snake.some(segment => 
                                  segment.x === reverseHead.x && segment.y === reverseHead.y);
            
            if (canReverse) {
                monster.direction = reverseDirection;
                head.x = reverseHead.x;
                head.y = reverseHead.y;
            } else {
                // 完全无路可走时保持原位，避免死亡
                return;
            }
        }
    }
    
    // 自撞检查 - 增加容错机制，只检查前半身避免过于严格
    const checkLength = Math.min(monster.snake.length, Math.floor(monster.snake.length * 0.6));
    const frontBody = monster.snake.slice(0, checkLength);
    if (frontBody.some(segment => segment.x === head.x && segment.y === head.y)) {
        // 尝试寻找安全方向而不是直接死亡
        const directions = [
            { x: GAME_CONFIG.GRID_SIZE, y: 0 },
            { x: -GAME_CONFIG.GRID_SIZE, y: 0 },
            { x: 0, y: GAME_CONFIG.GRID_SIZE },
            { x: 0, y: -GAME_CONFIG.GRID_SIZE }
        ];
        
        let foundSafeDirection = false;
        for (let dir of directions) {
            const testHead = {
                x: monster.snake[0].x + dir.x,
                y: monster.snake[0].y + dir.y
            };
            
            const wouldHitWall = testHead.x < 0 || testHead.x >= currentWorldWidth || 
                                testHead.y < 0 || testHead.y >= currentWorldHeight;
            const wouldHitSelf = monster.snake.some(segment => 
                segment.x === testHead.x && segment.y === testHead.y);
            
            if (!wouldHitWall && !wouldHitSelf) {
                monster.direction = dir;
                head.x = testHead.x;
                head.y = testHead.y;
                foundSafeDirection = true;
                break;
            }
        }
        
        if (!foundSafeDirection) {
            // 只有在完全无路可走时才死亡
            killMonster(monster);
            return;
        }
    }
    
    monster.snake.unshift(head);
    
    // 妖怪道具免疫系统 - 妖怪碰到道具时直接忽略，不产生任何效果
    const powerUpIndex = gameState.powerUps.findIndex(powerUp => powerUp.x === head.x && powerUp.y === head.y);
    if (powerUpIndex !== -1) {
        // 妖怪免疫道具效果，道具保持在原位不被消耗
        // 这确保妖怪不会意外触发道具或消耗玩家的道具
    }
    
    // 妖怪只吃食物来维持长度
    const foodIndex = gameState.foods.findIndex(food => food.x === head.x && food.y === head.y);
    if (foodIndex !== -1) {
        gameState.foods.splice(foodIndex, 1);
        
        // 生成新食物
        let newPos;
        do {
            newPos = getRandomPosition();
        } while (isPositionOccupied(newPos));
        
        gameState.foods.push({
            id: uuidv4(),
            x: newPos.x,
            y: newPos.y,
            value: Math.floor(Math.random() * 3) + 1
        });
    } else {
        monster.snake.pop(); // 没吃到食物就移除尾部
    }
}

// 杀死妖怪
function killMonster(monster) {
    monster.alive = false;
    console.log(`妖怪 ${monster.name} 已死亡`);
    
    // 延迟移除死亡妖怪，避免立即清理导致的引用问题
    setTimeout(() => {
        gameState.monsters.delete(monster.id);
        console.log(`清理死亡妖怪: ${monster.name}`);
    }, 1000);
}

// 检查妖怪与玩家的碰撞 - 支持玩家吃妖怪机制
function checkMonsterPlayerCollisions(monster) {
    const monsterHead = monster.snake[0];
    
    for (let [playerId, player] of gameState.players) {
        if (!player.alive) continue;
        
        // 检查妖怪头部是否撞到玩家身体
        const hitPlayerBody = player.snake.some(segment => 
            segment.x === monsterHead.x && segment.y === monsterHead.y);
        
        if (hitPlayerBody) {
            // 比较长度决定胜负
            if (player.snake.length > monster.snake.length) {
                // 玩家长度大于妖怪，玩家吃掉妖怪
                player.score += monster.scoreReward * 2; // 双倍奖励
                
                // 玩家蛇身增长（吃掉妖怪获得额外长度）
                const growthAmount = Math.floor(monster.snake.length / 3);
                for (let i = 0; i < growthAmount; i++) {
                    const tail = player.snake[player.snake.length - 1];
                    player.snake.push({ ...tail });
                }
                
                // 添加世界消息
                const message = `${player.name} 吃掉了 ${monster.name}，获得了强大的力量！`;
                addWorldMessage(message);
                
                killMonster(monster);
                break;
            } else {
                // 妖怪长度大于等于玩家，玩家被吃掉
                killPlayer(player, `被${monster.name}吃掉`);
                continue;
            }
        }
        
        // 检查玩家头部是否撞到妖怪身体
        const playerHead = player.snake[0];
        const hitMonsterBody = monster.snake.some(segment => 
            segment.x === playerHead.x && segment.y === playerHead.y);
        
        if (hitMonsterBody) {
            // 比较长度决定胜负
            if (player.snake.length > monster.snake.length) {
                // 玩家长度大于妖怪，玩家吃掉妖怪
                player.score += monster.scoreReward * 2; // 双倍奖励
                
                // 玩家蛇身增长（吃掉妖怪获得额外长度）
                const growthAmount = Math.floor(monster.snake.length / 3);
                for (let i = 0; i < growthAmount; i++) {
                    const tail = player.snake[player.snake.length - 1];
                    player.snake.push({ ...tail });
                }
                
                // 添加世界消息
                const message = `${player.name} 击败了 ${monster.name}，真是太厉害了！`;
                addWorldMessage(message);
                
                killMonster(monster);
                break;
            } else {
                // 妖怪长度大于等于玩家，玩家被击败
                killPlayer(player, `被${monster.name}击败`);
                continue;
            }
        }
    }
}

// 添加世界消息
function addWorldMessage(message) {
    const worldMessage = {
        id: uuidv4(),
        message: message,
        timestamp: Date.now()
    };
    
    gameState.worldMessages.push(worldMessage);
    
    // 只保留最近的10条消息
    if (gameState.worldMessages.length > 10) {
        gameState.worldMessages.shift();
    }
    
    // 立即广播世界消息给所有客户端
    broadcastWorldMessage(message, worldMessage.timestamp);
    
    console.log(`世界消息: ${message}`);
}

// 广播世界消息给所有客户端
function broadcastWorldMessage(message, timestamp) {
    const messageData = JSON.stringify({
        type: 'worldMessage',
        message: message,
        timestamp: timestamp
    });
    
    wss.clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(messageData);
        }
    });
}

// 妖怪配置 - 固定数量管理
const MONSTER_CONFIG = {
    TOTAL_COUNT: 6, // 地图上固定维持6只妖怪
    TYPE_DISTRIBUTION: {
        'DAWANG': 3,    // 大王洞大王 3只
        'LAOSHU': 2,    // 老鼠精 2只  
        'HUANGMEI': 1   // 黄眉大王 1只
    }
};

// 生成妖怪
function spawnMonster() {
    // 检查当前妖怪数量
    if (gameState.monsters.size >= MONSTER_CONFIG.TOTAL_COUNT) {
        return;
    }
    
    // 统计各类型活着的妖怪数量
    const typeCount = {
        'DAWANG': 0,
        'LAOSHU': 0,
        'HUANGMEI': 0
    };
    
    for (let monster of gameState.monsters.values()) {
        if (monster.alive) { // 只统计活着的妖怪
            if (monster.type === 'dawang') typeCount.DAWANG++;
            else if (monster.type === 'laoshu') typeCount.LAOSHU++;
            else if (monster.type === 'huangmei') typeCount.HUANGMEI++;
        }
    }
    
    // 找出需要补充的妖怪类型
    let spawnType = null;
    for (let [type, maxCount] of Object.entries(MONSTER_CONFIG.TYPE_DISTRIBUTION)) {
        if (typeCount[type] < maxCount) {
            spawnType = type;
            break;
        }
    }
    
    if (!spawnType) return;
    
    const monster = createMonster(spawnType);
    if (monster) {
        gameState.monsters.set(monster.id, monster);
        console.log(`生成妖怪: ${monster.name} (当前总数: ${gameState.monsters.size}, 活着: ${Array.from(gameState.monsters.values()).filter(m => m.alive).length})`);
    }
}

// 初始化妖怪 - 游戏开始时生成所有妖怪
function initializeMonsters() {
    console.log('初始化妖怪系统...');
    
    // 清空现有妖怪
    gameState.monsters.clear();
    
    // 按配置生成各类型妖怪
    for (let [type, count] of Object.entries(MONSTER_CONFIG.TYPE_DISTRIBUTION)) {
        for (let i = 0; i < count; i++) {
            const monster = createMonster(type);
            if (monster) {
                gameState.monsters.set(monster.id, monster);
                console.log(`初始化妖怪: ${monster.name}`);
            }
        }
    }
    
    console.log(`妖怪初始化完成，总数: ${gameState.monsters.size}`);
}

// 创建新玩家
function createPlayer(ws, name, avatar, worldWidth = GAME_CONFIG.WORLD_WIDTH, worldHeight = GAME_CONFIG.WORLD_HEIGHT) {
    const player = {
        id: uuidv4(),
        ws: ws,
        name: name || `玩家${Math.floor(Math.random() * 1000)}`,
        avatar: avatar || 0,
        snake: [],
        direction: { x: GAME_CONFIG.GRID_SIZE, y: 0 },
        score: 0,
        alive: true,
        color: `hsl(${Math.random() * 360}, 70%, 50%)`,
        effects: new Map(), // 道具效果
        lastMove: Date.now(),
        worldWidth: worldWidth,  // 玩家专属的世界宽度
        worldHeight: worldHeight // 玩家专属的世界高度
    };
    
    // 使用玩家专属的世界尺寸生成出生位置
    let startPos;
    do {
        startPos = getRandomPosition(player.worldWidth, player.worldHeight);
    } while (isPositionOccupied(startPos));
    
    // 初始化蛇身
    for (let i = 0; i < GAME_CONFIG.INITIAL_SNAKE_LENGTH; i++) {
        player.snake.push({
            x: startPos.x - i * GAME_CONFIG.GRID_SIZE,
            y: startPos.y
        });
    }
    
    return player;
}

// 移动蛇
function moveSnake(player) {
    if (!player.alive) return;
    
    // 检查是否被冰冻
    if (player.effects.has('frozen')) {
        return; // 被冰冻时不移动
    }
    
    const head = { ...player.snake[0] };
    head.x += player.direction.x;
    head.y += player.direction.y;
    
    // 边界检查 - 穿墙效果可以忽略边界
    if (!player.effects.has('ghost')) {
        if (head.x < 0 || head.x >= player.worldWidth || 
            head.y < 0 || head.y >= player.worldHeight) {
            console.log(`玩家 ${player.name} 撞墙: 位置(${head.x}, ${head.y}), 边界(${player.worldWidth}, ${player.worldHeight})`);
            killPlayer(player, 'wall');
            return;
        }
    } else {
        // 穿墙效果：从边界另一侧出现
        if (head.x < 0) head.x = player.worldWidth - GAME_CONFIG.GRID_SIZE;
        if (head.x >= player.worldWidth) head.x = 0;
        if (head.y < 0) head.y = player.worldHeight - GAME_CONFIG.GRID_SIZE;
        if (head.y >= player.worldHeight) head.y = 0;
    }
    
    // 自撞检查
    if (player.snake.some(segment => segment.x === head.x && segment.y === head.y)) {
        killPlayer(player, 'self');
        return;
    }
    
    player.snake.unshift(head);
    
    // 磁铁效果：吸引附近的食物
    if (player.effects.has('magnet')) {
        const magnetRange = GAME_CONFIG.GRID_SIZE * 3; // 磁铁范围
        for (let food of gameState.foods) {
            const distance = Math.abs(food.x - head.x) + Math.abs(food.y - head.y);
            if (distance <= magnetRange && distance > 0) {
                // 将食物向蛇头方向移动
                if (food.x < head.x) food.x += GAME_CONFIG.GRID_SIZE;
                else if (food.x > head.x) food.x -= GAME_CONFIG.GRID_SIZE;
                if (food.y < head.y) food.y += GAME_CONFIG.GRID_SIZE;
                else if (food.y > head.y) food.y -= GAME_CONFIG.GRID_SIZE;
            }
        }
    }
    
    // 检查食物碰撞
    const foodIndex = gameState.foods.findIndex(food => food.x === head.x && food.y === head.y);
    if (foodIndex !== -1) {
        const food = gameState.foods[foodIndex];
        let scoreMultiplier = player.effects.has('double') ? 2 : 1;
        
        // 多倍食物效果：额外增加分数倍数
        if (player.effects.has('multifood')) {
            scoreMultiplier *= 3; // 三倍食物分数
        }
        
        player.score += food.value * scoreMultiplier;
        gameState.foods.splice(foodIndex, 1);
        
        // 生成新食物
        let newPos;
        do {
            newPos = getRandomPosition();
        } while (isPositionOccupied(newPos));
        
        gameState.foods.push({
            id: uuidv4(),
            x: newPos.x,
            y: newPos.y,
            value: Math.floor(Math.random() * 3) + 1
        });
    } else {
        player.snake.pop(); // 没吃到食物就移除尾部
    }
    
    // 检查道具碰撞
    const powerUpIndex = gameState.powerUps.findIndex(powerUp => powerUp.x === head.x && powerUp.y === head.y);
    if (powerUpIndex !== -1) {
        const powerUp = gameState.powerUps[powerUpIndex];
        applyPowerUp(player, powerUp.type);
        gameState.powerUps.splice(powerUpIndex, 1);
        
        // 如果吃掉的是翻倍道具，立即在随机位置刷新一个新的翻倍道具
        if (powerUp.type === 'double') {
            generateSpecificPowerUp('double');
        } else {
            // 生成新道具
            generateNewPowerUp();
        }
    }
    
    // 检查与其他蛇的碰撞
    checkSnakeCollisions(player);
}

// 应用道具效果
function applyPowerUp(player, type) {
    switch (type.toLowerCase()) {
        case 'mine':
            // 地雷效果：玩家死亡
            killPlayer(player, 'mine');
            break;
            
        case 'double':
            // 翻倍道具：蛇的长度翻倍
            const currentLength = player.snake.length;
            const tail = player.snake[player.snake.length - 1];
            
            // 在蛇尾添加新的身体段
            for (let i = 0; i < currentLength; i++) {
                player.snake.push({ ...tail });
            }
            
            // 增加分数
            player.score += currentLength * 5;
            break;
            
        case 'speed':
            const powerUp = POWER_UP_TYPES[type.toUpperCase()];
            if (powerUp) {
                player.effects.set('speed', Date.now() + powerUp.duration);
            }
            break;
        case 'invincible':
            const invinciblePowerUp = POWER_UP_TYPES[type.toUpperCase()];
            if (invinciblePowerUp) {
                player.effects.set('invincible', Date.now() + invinciblePowerUp.duration);
            }
            break;
        case 'shrink':
            if (player.snake.length > 3) {
                const removeCount = Math.min(3, player.snake.length - 3);
                player.snake.splice(-removeCount, removeCount);
                player.score += removeCount * 5; // 补偿分数
            }
            break;
        case 'grow':
            // 增加蛇的长度
            const growTail = player.snake[player.snake.length - 1];
            for (let i = 0; i < 3; i++) {
                player.snake.push({ ...growTail });
            }
            player.score += 10; // 奖励分数
            break;
        case 'invisible':
            const invisiblePowerUp = POWER_UP_TYPES[type.toUpperCase()];
            if (invisiblePowerUp) {
                player.effects.set('invisible', Date.now() + invisiblePowerUp.duration);
            }
            break;
        case 'shield':
            const shieldPowerUp = POWER_UP_TYPES[type.toUpperCase()];
            if (shieldPowerUp) {
                player.effects.set('shield', Date.now() + shieldPowerUp.duration);
            }
            break;
        case 'magnet':
            const magnetPowerUp = POWER_UP_TYPES[type.toUpperCase()];
            if (magnetPowerUp) {
                player.effects.set('magnet', Date.now() + magnetPowerUp.duration);
            }
            break;
        case 'teleport':
            // 传送到地图随机位置
            const teleportPos = getRandomPosition(player.worldWidth, player.worldHeight);
            player.snake[0] = { x: teleportPos.x, y: teleportPos.y };
            player.score += 15; // 奖励分数
            break;
        case 'freeze':
            // 冰冻其他玩家
            const freezePowerUp = POWER_UP_TYPES[type.toUpperCase()];
            if (freezePowerUp) {
                for (let otherPlayer of gameState.players.values()) {
                    if (otherPlayer.id !== player.id && otherPlayer.alive) {
                        otherPlayer.effects.set('frozen', Date.now() + freezePowerUp.duration);
                    }
                }
            }
            break;
        case 'lightning':
            // 闪电攻击：消除附近的其他蛇段
            const head = player.snake[0];
            const lightningRange = 60; // 3格范围
            for (let otherPlayer of gameState.players.values()) {
                if (otherPlayer.id !== player.id && otherPlayer.alive) {
                    const distance = Math.abs(otherPlayer.snake[0].x - head.x) + Math.abs(otherPlayer.snake[0].y - head.y);
                    if (distance <= lightningRange) {
                        // 缩短被攻击蛇的长度
                        const removeCount = Math.min(2, otherPlayer.snake.length - 1);
                        otherPlayer.snake.splice(-removeCount, removeCount);
                    }
                }
            }
            player.score += 20; // 奖励分数
            break;
        case 'multifood':
            // 多倍食物效果
            const multiFoodPowerUp = POWER_UP_TYPES[type.toUpperCase()];
            if (multiFoodPowerUp) {
                player.effects.set('multifood', Date.now() + multiFoodPowerUp.duration);
            }
            break;
        case 'ghost':
            // 穿墙效果
            const ghostPowerUp = POWER_UP_TYPES[type.toUpperCase()];
            if (ghostPowerUp) {
                player.effects.set('ghost', Date.now() + ghostPowerUp.duration);
            }
            break;
        case 'reverse':
            // 反转其他玩家的方向
            for (let otherPlayer of gameState.players.values()) {
                if (otherPlayer.id !== player.id && otherPlayer.alive) {
                    // 反转方向
                    const directionMap = {
                        'up': 'down',
                        'down': 'up',
                        'left': 'right',
                        'right': 'left'
                    };
                    otherPlayer.direction = directionMap[otherPlayer.direction] || otherPlayer.direction;
                }
            }
            player.score += 25; // 奖励分数
            break;
    }
}

// 生成特定类型道具
function generateSpecificPowerUp(powerUpType) {
    // 检查翻倍道具数量限制
    if (powerUpType === 'double') {
        const currentDoubleCount = gameState.powerUps.filter(p => p.type === 'double').length;
        if (currentDoubleCount >= 5) {
            return; // 已达到翻倍道具数量上限
        }
    }
    
    let pos;
    do {
        pos = getRandomPosition();
    } while (isPositionOccupied(pos) || 
             gameState.foods.some(food => food.x === pos.x && food.y === pos.y));
    
    let powerUpConfig;
    if (powerUpType === 'double') {
        powerUpConfig = POWER_UP_TYPES.DOUBLE_SCORE;
    } else {
        return; // 目前只支持翻倍道具的特定生成
    }
    
    gameState.powerUps.push({
        id: uuidv4(),
        x: pos.x,
        y: pos.y,
        type: powerUpConfig.id,
        color: powerUpConfig.color
    });
}

// 生成新道具
function generateNewPowerUp() {
    let pos;
    do {
        pos = getRandomPosition();
    } while (isPositionOccupied(pos) || 
             gameState.foods.some(food => food.x === pos.x && food.y === pos.y));
    
    // 检查翻倍道具数量，如果已达上限则从权重中移除
    const currentDoubleCount = gameState.powerUps.filter(p => p.type === 'double').length;
    const doubleWeight = currentDoubleCount >= 5 ? 0 : 2;
    
    // 道具权重分布 - 翻倍道具数量限制在5个以内
    const weightedPowerUps = [
        { type: POWER_UP_TYPES.SPEED_BOOST, weight: 30 },
        { type: POWER_UP_TYPES.GROW, weight: 25 },
        { type: POWER_UP_TYPES.DOUBLE_SCORE, weight: doubleWeight }, // 动态权重
        { type: POWER_UP_TYPES.MAGNET, weight: 18 },
        { type: POWER_UP_TYPES.SHIELD, weight: 15 },
        { type: POWER_UP_TYPES.INVISIBLE, weight: 12 },
        { type: POWER_UP_TYPES.INVINCIBLE, weight: 10 },
        { type: POWER_UP_TYPES.SHRINK, weight: 15 },
        { type: { id: 'mine', color: '#FF0000', name: '地雷' }, weight: 1 }
    ];
    
    const totalWeight = weightedPowerUps.reduce((sum, item) => sum + item.weight, 0);
    let random = Math.random() * totalWeight;
    
    let selectedType = weightedPowerUps[0].type;
    for (const item of weightedPowerUps) {
        if (item.weight > 0) { // 只考虑权重大于0的道具
            random -= item.weight;
            if (random <= 0) {
                selectedType = item.type;
                break;
            }
        }
    }
    
    gameState.powerUps.push({
        id: uuidv4(),
        x: pos.x,
        y: pos.y,
        type: selectedType.id,
        color: selectedType.color
    });
}

// 检查蛇之间的碰撞
function checkSnakeCollisions(currentPlayer) {
    const head = currentPlayer.snake[0];
    
    for (let [playerId, otherPlayer] of gameState.players) {
        if (playerId === currentPlayer.id || !otherPlayer.alive) continue;
        
        // 如果当前玩家隐身，跳过碰撞检测
        if (currentPlayer.effects.has('invisible')) continue;
        
        // 检查是否撞到其他蛇的身体
        for (let i = 0; i < otherPlayer.snake.length; i++) {
            const segment = otherPlayer.snake[i];
            if (head.x === segment.x && head.y === segment.y) {
                // 如果当前玩家有无敌或护盾效果，跳过碰撞
                if (currentPlayer.effects.has('invincible') || currentPlayer.effects.has('shield')) {
                    // 护盾被消耗
                    if (currentPlayer.effects.has('shield')) {
                        currentPlayer.effects.delete('shield');
                    }
                    continue;
                }
                
                // 比较蛇的长度，长蛇吃短蛇
                if (currentPlayer.snake.length > otherPlayer.snake.length) {
                    // 当前玩家吃掉其他玩家
                    const bonus = Math.floor(otherPlayer.snake.length / 2);
                    currentPlayer.score += bonus * 10;
                    
                    // 增长当前玩家的蛇
                    for (let j = 0; j < bonus; j++) {
                        const tail = currentPlayer.snake[currentPlayer.snake.length - 1];
                        currentPlayer.snake.push({ ...tail });
                    }
                    
                    killPlayer(otherPlayer, 'eaten');
                } else if (currentPlayer.snake.length < otherPlayer.snake.length) {
                    // 当前玩家被吃掉
                    const bonus = Math.floor(currentPlayer.snake.length / 2);
                    otherPlayer.score += bonus * 10;
                    
                    // 增长其他玩家的蛇
                    for (let j = 0; j < bonus; j++) {
                        const tail = otherPlayer.snake[otherPlayer.snake.length - 1];
                        otherPlayer.snake.push({ ...tail });
                    }
                    
                    killPlayer(currentPlayer, 'eaten');
                } else {
                    // 长度相同，都死亡
                    killPlayer(currentPlayer, 'collision');
                    killPlayer(otherPlayer, 'collision');
                }
                return;
            }
        }
    }
}

// 杀死玩家
function killPlayer(player, cause = 'unknown') {
    player.alive = false;
    player.effects.clear();
    
    // 通知玩家死亡
    if (player.ws.readyState === WebSocket.OPEN) {
        player.ws.send(JSON.stringify({
            type: 'playerDied',
            score: player.score,
            length: player.snake.length,
            cause: cause
        }));
    }
}

// 更新道具效果
function updateEffects() {
    const now = Date.now();
    for (let player of gameState.players.values()) {
        for (let [effect, expireTime] of player.effects) {
            if (now > expireTime) {
                player.effects.delete(effect);
            }
        }
    }
}

// 广播游戏状态
function broadcastGameState() {
    const players = Array.from(gameState.players.values()).map(player => ({
        id: player.id,
        name: player.name,
        avatar: player.avatar,
        snake: player.snake,
        score: player.score,
        alive: player.alive,
        color: player.color,
        effects: Array.from(player.effects.keys())
    }));
    
    // 转换妖怪数据
    const monsters = Array.from(gameState.monsters.values()).map(monster => ({
        id: monster.id,
        type: monster.type,
        name: monster.name,
        level: monster.level,
        snake: monster.snake,
        color: monster.color,
        textColor: monster.textColor,
        size: monster.size,
        alive: monster.alive
    }));
    
    const message = JSON.stringify({
        type: 'gameState',
        players: players,
        monsters: monsters,
        foods: gameState.foods,
        powerUps: gameState.powerUps,
        worldMessages: gameState.worldMessages,
        leaderboard: getLeaderboard()
    });
    
    // 发送给所有连接的客户端
    wss.clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(message);
        }
    });
}

// 获取排行榜
function getLeaderboard() {
    return Array.from(gameState.players.values())
        .filter(player => player.alive)
        .sort((a, b) => b.score - a.score)
        .slice(0, 10)
        .map((player, index) => ({
            rank: index + 1,
            id: player.id,
            name: player.name,
            score: player.score,
            length: player.snake.length
        }));
}

// WebSocket连接处理
wss.on('connection', (ws) => {
    console.log('新玩家连接');
    
    ws.on('message', (message) => {
        try {
            const data = JSON.parse(message);
            
            switch (data.type) {
                case 'updateCanvasSize':
                    console.log('收到updateCanvasSize请求:', data);
                    // 存储该连接的画布尺寸，稍后在玩家加入时使用
                    if (data.canvasWidth && data.canvasHeight) {
                        ws.canvasWidth = data.canvasWidth;
                        ws.canvasHeight = data.canvasHeight;
                        ws.worldWidth = data.canvasWidth * 3;
                        ws.worldHeight = data.canvasHeight * 3;
                        console.log(`连接的世界尺寸设置为: ${ws.worldWidth}x${ws.worldHeight}`);
                    }
                    break;
                    
                case 'join':
                    console.log('收到join请求:', data);
                    if (gameState.players.size >= GAME_CONFIG.MAX_PLAYERS) {
                        ws.send(JSON.stringify({ type: 'error', message: '服务器已满' }));
                        return;
                    }
                    
                    // 使用连接特定的世界尺寸创建玩家，如果没有则使用默认值
                    const playerWorldWidth = ws.worldWidth || GAME_CONFIG.WORLD_WIDTH;
                    const playerWorldHeight = ws.worldHeight || GAME_CONFIG.WORLD_HEIGHT;
                    const player = createPlayer(ws, data.name, data.avatar, playerWorldWidth, playerWorldHeight);
                    console.log(`玩家 ${player.name} 使用专属世界尺寸: ${player.worldWidth}x${player.worldHeight}`);
                    
                    gameState.players.set(player.id, player);
                    ws.playerId = player.id;
                    
                    // 如果是第一个玩家，初始化游戏
                    if (gameState.players.size === 1) {
                        generateFood();
                        generatePowerUps();
                        gameState.gameStarted = true;
                    }
                    
                    const joinedMessage = {
                        type: 'joined',
                        playerId: player.id,
                        playerName: player.name,
                        worldWidth: player.worldWidth,
                        worldHeight: player.worldHeight
                    };
                    console.log('发送joined消息:', joinedMessage);
                    ws.send(JSON.stringify(joinedMessage));
                    
                    console.log(`玩家 ${player.name} 加入游戏`);
                    break;
                    
                case 'move':
                    const currentPlayer = gameState.players.get(ws.playerId);
                    if (currentPlayer && currentPlayer.alive) {
                        const now = Date.now();
                        const speedBoost = currentPlayer.effects.has('speed') ? 0.7 : 1;
                        const minInterval = GAME_CONFIG.GAME_SPEED * speedBoost;
                        
                        if (now - currentPlayer.lastMove >= minInterval) {
                            // 防止反向移动
                            const newDir = data.direction;
                            const currentDir = currentPlayer.direction;
                            
                            if (!(newDir.x === -currentDir.x && newDir.y === -currentDir.y)) {
                                currentPlayer.direction = newDir;
                            }
                            currentPlayer.lastMove = now;
                        }
                    }
                    break;
                    
                case 'respawn':
                    const deadPlayer = gameState.players.get(ws.playerId);
                    if (deadPlayer && !deadPlayer.alive) {
                        // 使用连接特定的世界尺寸重生玩家，如果没有则使用死亡玩家的世界尺寸
                        const playerWorldWidth = ws.worldWidth || deadPlayer.worldWidth || GAME_CONFIG.WORLD_WIDTH;
                        const playerWorldHeight = ws.worldHeight || deadPlayer.worldHeight || GAME_CONFIG.WORLD_HEIGHT;
                        const newPlayer = createPlayer(ws, deadPlayer.name, deadPlayer.avatar, playerWorldWidth, playerWorldHeight);
                        newPlayer.id = deadPlayer.id;
                        gameState.players.set(newPlayer.id, newPlayer);
                        
                        console.log(`玩家 ${newPlayer.name} 重生，使用世界尺寸: ${newPlayer.worldWidth}x${newPlayer.worldHeight}`);
                        
                        ws.send(JSON.stringify({
                            type: 'respawned',
                            playerId: newPlayer.id
                        }));
                    }
                    break;
            }
        } catch (error) {
            console.error('处理消息错误:', error);
        }
    });
    
    ws.on('close', () => {
        if (ws.playerId) {
            const player = gameState.players.get(ws.playerId);
            if (player) {
                console.log(`玩家 ${player.name} 离开游戏`);
                gameState.players.delete(ws.playerId);
            }
        }
    });
});

// 游戏主循环
// 道具生成计数器
let powerUpSpawnCounter = 0;
const POWER_UP_SPAWN_INTERVAL = 20; // 每20个游戏循环生成一个额外道具
let monsterSpawnCounter = 0;
const MONSTER_SPAWN_INTERVAL = 50; // 每50个游戏循环尝试生成妖怪（提高生成频率）

setInterval(() => {
    if (gameState.gameStarted && gameState.players.size > 0) {
        // 移动所有活着的蛇
        for (let player of gameState.players.values()) {
            if (player.alive) {
                moveSnake(player);
            }
        }
        
        // 移动所有妖怪
        for (let monster of gameState.monsters.values()) {
            if (monster.alive) {
                moveMonster(monster);
                checkMonsterPlayerCollisions(monster);
            }
        }
        
        // 定期生成额外道具以增加可玩性
        powerUpSpawnCounter++;
        if (powerUpSpawnCounter >= POWER_UP_SPAWN_INTERVAL && gameState.powerUps.length < GAME_CONFIG.POWER_UP_COUNT * 1.5) {
            generateNewPowerUp();
            powerUpSpawnCounter = 0;
        }
        
        // 定期生成妖怪
        monsterSpawnCounter++;
        if (monsterSpawnCounter >= MONSTER_SPAWN_INTERVAL) {
            spawnMonster();
            monsterSpawnCounter = 0;
        }
        
        // 更新道具效果
        updateEffects();
        
        // 广播游戏状态
        broadcastGameState();
    }
}, GAME_CONFIG.GAME_SPEED);

// 初始化妖怪系统
initializeMonsters();

console.log('多人贪吃蛇游戏服务器启动完成!');